package com.siriuscloud.holidayreservation.web;

import com.siriuscloud.holidayreservation.domain.Matter;
import com.siriuscloud.holidayreservation.domain.vo.MatterVo;
import com.siriuscloud.holidayreservation.service.MatterService;
import com.siriuscloud.holidayreservation.utils.MyPage;
import com.siriuscloud.holidayreservation.utils.MyPageVo;
import com.siriuscloud.holidayreservation.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
public class MatterController {
    @Resource
    private MatterService matterService;

    // 获取该部门下所有事项
    @GetMapping("/department/{departmentId}/matters/all")
    public R list(@PathVariable Long departmentId, @RequestParam(required = false) String name) throws Exception {
        try {
            List<Matter> matterList = matterService.getAllByDepartmentId(departmentId, name);
            return R.ok().data(matterList);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    @GetMapping("/departments/{departmentId}/matters/page")
    public R getAllByPage(
            MyPage page,
            @RequestParam(required = false) String name,
            @PathVariable String departmentId
    ) {
        MyPageVo<MatterVo> allByPage = matterService.getAllByPage(page, name, departmentId);
        HashMap<String, Object> data = new HashMap<>();
        data.put("total", allByPage.getTotal());
        data.put("rows", allByPage.getRecords());
        return R.ok().data(data);
    }

    @PostMapping("/department/{departmentId}/matter")
    public R add(
            @RequestBody Matter matter,
            @PathVariable String departmentId) throws Exception {
        matter.setDepartmentId(departmentId);
        Boolean flag = matterService.create(matter);
        if (flag) {
            return R.ok().msg("新增成功");
        }
        return R.error().msg("新增失败");
    }

    @PutMapping("/matter")
    public R update(@RequestBody Matter matter) {
        Boolean flag = matterService.update(matter);
        if (flag) {
            return R.ok().msg("修改成功");
        }
        return R.error().msg("修改失败");
    }

    @DeleteMapping("/matter/{id}")
    public R delete(@PathVariable Long id) {
        Boolean flag = matterService.delete(id);
        if (flag) {
            return R.ok().msg("删除成功");
        }
        return R.error().msg("删除失败");
    }

    @GetMapping("/matter/{id}")
    public R delete(@PathVariable String id) {
        Matter matter = matterService.getById(id);
        return R.ok().data(matter);
    }

}
